PHP - Android Layout findViews 程式產生器

findViews 程式產生器

因為我有變數取前置元(prefix)的習慣,
且我有一定的開發習慣,因為開始開發一個新頁面時,突然覺得我要將所有含id的元件都要取變數名及轉成物件,這樣的動作還滿常有的,
雖然我已經有寫替換器了,但覺得還是太浪費我時間了,所以我寫了一個findviews產生器

直接將整個xml Layout貼上去,用PHP preg_match_all 取得內容(多虧以前我愛開發自動產生器加上我又學會爬文及PHP,瞬間要有一個小型工具容易了許多)

就這樣瞬間做好了。
我想以前只要Layout XML撰寫完,只要變數命名正確,
其實很快就寫好了。

你說命名重不重要,當然重要啦,這樣我要產生程式碼比較容易呀。

<?php
	$sourceText = "";
	$targetText = "";
	
	if($_POST['submit']!="") {
		$remove_character = array("\n", "\r\n", "\r", "<p>", "</p>");

		$sourceText = str_replace("\\","",$_POST['sourceText']);
		$targetText = "";
		$targetFindViews = "";
		$targetPrivate = "";

		preg_match_all("|id/(.*?)\"|U", $sourceText, $matchs);
		$i =0;
		foreach($matchs as $vals) {	
		    if($i==0) {
				//continue;
			} else {
				foreach($vals as $val) {
					$objControl =  '';
					if (strpos($val, 'txtv_') !== false) { $objControl = 'TextView' ;}
					if (strpos($val, 'btn_') !== false) { $objControl = 'Button' ;}
					if (strpos($val, 'lin_') !== false) { $objControl = 'LinearLayout'; }
					if (strpos($val, 'img_') !== false) { $objControl = 'ImageView'; }
					if (strpos($val, 'edit_') !== false) { $objControl = 'EditText' ;}
					if (strpos($val, 'spinner_') !== false) { $objControl = 'Spinner'; }
					
					$targetPrivate = $targetPrivate."\r\n"."private $objControl $val;";
					$targetFindViews = $targetFindViews."\r\n    "."this.$val = ($objControl)findViewById(R.id.$val);";						
				}
			}
			$i++;
		}		
		
		$targetFindViews = "private void findViews(){ $targetFindViews\r\n}";
		$targetText = "$targetPrivate\n\n$targetFindViews";
	}
?>

 
<html>
	<head>
		<title>Layout程式開發器</title>
	</head>
	<body>
		<div>
			<div>
				<h1>Layout Tool</h1>
			</div>
			<form method="POST" action="http://localhost/layout_tool.php" >                
				<fieldset>
					<div>
						<label>
							Layout XML
						</label>
						<div >
							<textarea id="sourceText" name="sourceText" cols="100" rows="5"   ><?=$sourceText?></textarea>
						</div>
					</div>					
					<div >
						<div >
							<input name="submit" type="submit" id="replace" tabindex="3"  value="產生程式碼">
						</div>
					</div>

					<div>
						<label class="col-md-2 control-label" for="password">
							程式碼
						</label>
						<div >
							<textarea id="targetText" name="targetText" cols="100" rows="30" ><?=$targetText?></textarea>
						</div>
					</div>	
				</fieldset>	
			</form>
		</div>		
	</body>
</html>